package com.yz.jdd.module.cashier.result;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PayConfig;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.Tools;
import com.yz.jdd.module.cashier.CashierActivity;
import com.yz.jdd.module.cashier.scanpay.ScanpayActivity;
import com.yz.jdd.network.request.Request_Pay;
import com.yz.jdd.voice.OrderVoice;
import com.yz.jdd.voice.SpeechUtilOffline;

/**
 * Created by shibin on 2016/12/29.
 * 收款/退款/储值/撤销--失败页
 */

public class PayFailureActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_detail_type;
    private TextView title;
    private String payType = "";
    private String orderType = "";
    private String resultCode = "";
    private String strVoiceType = "";
    private Request_Pay request_pay;
    private TextView tvRight;

    private TextView status;
    private TextView message;
    private TextView amountType;
    private TextView detailKey1;
    private LinearLayout detailLayout1;
    private TextView detailKeyPaytype;
    private TextView detailValuePaytype;
    private LinearLayout paytype_layout;
    private TextView detailValue1;
    private String dishModel;
    private String from;
    private Button pay_btn_complete;
    private int delatedTime = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_failure);

        initView();
    }

    void initView() {
        request_pay = (Request_Pay) getIntent().getSerializableExtra(PayConfig.INTENT_ORDER_FROM);
        pay_btn_complete = findViewById(R.id.pay_btn_complete);
        title = findViewById(R.id.title_nav);
        message = findViewById(R.id.payresult_message);
        status = findViewById(R.id.payresult_status);
        amountType = findViewById(R.id.payresult_amount_type);
        from = request_pay.getFrom();
        detailLayout1 = findViewById(R.id.detail_layout1);
        detailKey1 = findViewById(R.id.detail_key1);
        detailKeyPaytype = findViewById(R.id.detailkey_paytype);

        detailValue1 = findViewById(R.id.detail_value1);
        detailValuePaytype = findViewById(R.id.detailvalue_paytype);
        paytype_layout = findViewById(R.id.paytype_layout);

        findViewById(R.id.payresult_icon).setBackgroundResource(R.mipmap.casher_failure_error);
        findViewById(R.id.pay_btn_complete).setOnClickListener(this);
        findViewById(R.id.back_nav).setVisibility(View.GONE);
        tvRight = (TextView) findViewById(R.id.right_nav);
        tvRight.setOnClickListener(this);
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("完成");
//        findViewById(R.id.back_nav).setVisibility(View.GONE);
        ((TextView) findViewById(R.id.title_nav)).setText("收款结果");
        if (request_pay != null) {
            orderType = request_pay.getOrderType();
            resultCode = request_pay.getResultCode();
            message.setText(request_pay.getPayResultMessage());
            //区分交易，储值，退款
            if ("refund".equals(from)) {
                LogUtils.d(" ======退款结果");
                //退款显示字段：退款金额，退款方式
                title.setText("退款结果");
                //30081 退款优化 退款中状态
                if ("30081".equals(resultCode)) {
                    status.setText("退款中");
                } else {
                    status.setText("退款受理失败");
                }
                amountType.setText("申请退款金额");
                ((TextView) findViewById(R.id.txt_pre_refundmoney)).setText(request_pay.getRefundMoney());
                detailKeyPaytype.setText("退款方式");
//                detailLayout1.setVisibility(View.GONE);
                detailKey1.setText("申请退款金额");
                detailValue1.setText("¥" + request_pay.getRefundMoney());

                if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE) && SpeechUtilOffline.getInstance(PayFailureActivity.this) != null) {
                    OrderVoice orderVoice = new OrderVoice();
                    orderVoice.setContent("退款受理失败");
                    SpeechUtilOffline.getInstance(PayFailureActivity.this).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                }

            } else {
                if (PayConfig.TYPE_ORDER_DEAL.equals(orderType) || PayConfig.TYPE_ORDER_DISH.equals(orderType)) {//支付信息
                    LogUtils.d(" ======支付结果");
                    //支付显示字段：应收金额、实收金额、收款方式
                    delatedTime = PreferencesUtils.getInt(PayFailureActivity.this, BaseConfigs.PREF_FAIL_HINT_TIME, 0);
                    if (delatedTime != 0) {
                        pay_btn_complete.setText("确定（" + delatedTime + "S）");
                        mHandler.postDelayed(runnableDelated, 1000);
                    }

                    title.setText("支付结果");
                    status.setText("收款失败");
                    amountType.setText("实付金额");
                    detailKey1.setText("订单金额");
                    detailKeyPaytype.setText("收款方式");
                    detailValue1.setText("¥" + Tools.getSafeString(request_pay.getTotalAmount(), "0.00"));
                } else {
                    if (PayConfig.TYPE_ORDER_RECHARGE.equals(orderType)) {//储值信息
                        LogUtils.d(" ======储值结果");
                        //储值显示字段：储值金额、会员卡号、收款方式
                        title.setText("储值结果");
                        status.setText("储值失败");
                        amountType.setText("储值金额");
                        detailKey1.setText("会员卡号");
                        detailValue1.setText(Tools.getSafeString(request_pay.getMemberMobile()));
                        detailKeyPaytype.setText("收款方式");
                    } else {
                        if (PayConfig.TYPE_ORDER_CANCEL.equals(orderType)) {
                            LogUtils.d(" ======撤销结果");
                            title.setText("收款结果");
                            status.setText(Tools.getSafeString(request_pay.getCancelResultTitle(), ""));
                            amountType.setText("实收金额");
                            //撤销订单显示字段：应收金额，支付方式
                            detailKey1.setText("应收金额");
                            detailValue1.setText("¥" + Tools.getSafeString(request_pay.getTotalAmount(), "0.00"));
                            detailKeyPaytype.setText("支付方式");
                        }
                    }
                }
            }

            payType = request_pay.getPayType();
            if (PayConfig.TYPE_PAY_CASH.equals(payType)) {
                detailValuePaytype.setText(getString(R.string.txt_pay_cash));
                strVoiceType = "现金";
            } else {
                if (PayConfig.TYPE_PAY_ALIPAY.equals(payType)) {
                    detailValuePaytype.setText(getString(R.string.txt_pay_ali));
                    strVoiceType = "支付宝";
                } else {
                    if (PayConfig.TYPE_PAY_MEMBERCARD.equals(payType)) {
                        detailValuePaytype.setText(getString(R.string.txt_pay_card));
                        strVoiceType = "会员卡";
                    } else {
                        if (PayConfig.TYPE_PAY_WEIXIN.equals(payType)) {
                            detailValuePaytype.setText("微信");
                            strVoiceType = "微信";
                        } else {
                            if (PayConfig.TYPE_PAY_YUNSHANFU.equals(payType)) {
                                detailValuePaytype.setText("云闪付");
                                strVoiceType = "云闪付";
                            } else {
                                if (PayConfig.TYPE_PAY_UNION.equals(payType)) {
                                    detailValuePaytype.setText("银联");
                                    strVoiceType = "银联";
                                } else {
                                    if (PayConfig.TYPE_PAY_MINISTOREVALUE.equals(payType)) {
                                        detailValuePaytype.setText("余额支付");
                                        strVoiceType = "余额支付";
                                    } else {
                                        if (PayConfig.TYPE_PAY_SCAN.equals(payType)) {
                                            detailValuePaytype.setText("扫码");
                                            strVoiceType = "扫码";
                                            paytype_layout.setVisibility(View.GONE);
                                        } else {
                                            detailValuePaytype.setText("扫码");
                                            paytype_layout.setVisibility(View.GONE);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            /**
             * 语音播报支付方式+收款失败
             */
            if (!PayConfig.TYPE_ORDER_CANCEL.equals(orderType) && !PayConfig.TYPE_ORDER_REFUND.equals(orderType) && !"refund".equals(from)) {
                try {
                    String playVoice = "收款失败";  // strVoiceType +
                    if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE) && SpeechUtilOffline.getInstance(getApplicationContext()) != null) {
                        LogUtils.e("=== PayFailureActivity play: " + playVoice);
                        OrderVoice orderVoice = new OrderVoice();
                        orderVoice.setContent(playVoice);
                        SpeechUtilOffline.getInstance(getApplicationContext()).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

    private Handler mHandler = new Handler();
    private Runnable runnableDelated = new Runnable() {
        @Override
        public void run() {
            delatedTime--;
            pay_btn_complete.setText("确定（" + delatedTime + "S）");
            if (delatedTime == 0) {
                payComplete();
            } else {
                mHandler.postDelayed(this, 1000);
            }
        }
    };

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.pay_btn_complete) {
            payComplete();
        }
        if (v.getId() == R.id.back_nav) {
            payComplete();
        }
        if (v.getId() == R.id.right_nav) {
            RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
            finish();
        }
    }

    /**
     * 完成
     */
    private void payComplete() {
        boolean pos_fixed = PreferencesUtils.getBoolean(this, BaseConfigs.BOOLEAN_POS_FIXED_AMOUNT, false);
        RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
        String code = request_pay.getCode();
        if (!"refund".equals(from)) {
            if (PayConfig.TYPE_ORDER_DISH.equals(orderType)) {
//                //支付异常需重新收款
//                if (PayConfig.MODEL_DISH_AFTER.equals(dishModel) && ("2403".equals(code) || "2402".equals(code))) {
//                    IntentHandler.startFrontofficeManagementActivity(this, request_pay.getOrderId());
//                }
            } else {
                if (pos_fixed) {
                    intentFixedScanpay();
                } else {
                    Intent intent = new Intent(PayFailureActivity.this, CashierActivity.class);
                    intent.putExtra(PayConfig.INTENT_ORDER_REPAY, request_pay.getTotalAmount());
                    startActivity(intent);
                }
            }
        } else {
            RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
            if (PayConfig.TYPE_ORDER_DEAL.equals(orderType) || PayConfig.TYPE_ORDER_RECHARGE.equals(orderType)) {
                boolean flag = PreferencesUtils.getBoolean(this, BaseConfigs.CASHIER_REFUND, false);
                if (flag) {
                    if (pos_fixed) {
                        intentFixedScanpay();
                    } else {
                        startActivity(new Intent(PayFailureActivity.this, CashierActivity.class));
                    }
                }
            }
        }
        finish();
    }

    @Override
    protected void onStop() {
        mHandler.removeCallbacks(runnableDelated);
        super.onStop();
    }

    /**
     * 跳转固定金额扫码收款
     */
    private void intentFixedScanpay() {
        Request_Pay request_pay = new Request_Pay();
        request_pay.setOrderType(PayConfig.TYPE_ORDER_DEAL);
        request_pay.setTotalAmount(PreferencesUtils.getString(this, BaseConfigs.POS_FIXED_AMOUNT_VALUE, ""));
        request_pay.setFrom(PayConfig.INIENT_FIXED_SCAN);
        Intent intent = new Intent(this, ScanpayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(PayConfig.INTENT_ORDER_FROM, request_pay);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    //禁用物理返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            payComplete();
            return true;
        }
        return false;
    }

}
